# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: threading_condition.py 
@time: 2019/7/31 下午1:34
@note:
判断线程是否在运行
Condition对象代替Event对象对单一线程重复执行
"""
from threading import Thread, Condition
import  time


class PeriodicTimer:

    def __init__(self, interval):

        self._interval = interval
        self._flag =0
        self._cv = Condition()

    def start(self):

        t = Thread(target=self.run)
        t.daemon = True
        t.start()

    def run(self):

        while True:
            time.sleep(self._interval)
            with self._cv:
                self._flag ^= 1
                self._cv.notify_all()

    def wait_for_tick(self):

        with self._cv:
            last_flag = self._flag
            while last_flag == self._flag:
                self._cv.wait()


ptimer = PeriodicTimer(5)
ptimer.start()


# 在同一时间执行两个线程
def countdown(nticks):

    while nticks > 0:
        ptimer.wait_for_tick()
        print('T-minus', nticks)
        nticks -= 1

def countup(last):

    n = 0
    while n < last:
        ptimer.wait_for_tick()
        print('Counting', n)
        n += 1


Thread(target=countdown, args=(10,)).start()
Thread(target=countup, args=(5,)).start()
